<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Models\V1\ApplyDorms;
use App\Models\V1\NewArrival;
use App\Models\V1\NewStudent;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Log;
class DormsCollectController extends Controller
{
    /**
     * 显示志愿填报汇总数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $codes = $this->getEnrollmentCodes();
        $data['codes'] = $codes;
        $arrival_code = $this->getArrivalCodes();
        $data['arrival_code'] = $arrival_code;
        
        $Info = NewStudent::get();
        if(empty($Info)){
            return view('v1.collect.dorms');
        }
        $enrollment_directory = array();
        for($i=0;$i<count($Info);$i++){
            if(!in_array($Info[$i]->enrollment_directory, $enrollment_directory)){
                $enrollment_directory[] = $Info[$i]->enrollment_directory;
            }
        }
        $data['enrollment_directory'] = $enrollment_directory;
        return view('v1.collect.dorms', $data);
    }

    /**
     * 获取志愿填报汇总数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];
        // 获取符合查询条件的班级数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');
        $enrollment_directory = $request->input('enrollment_directory');
        $arrival_code = !empty($request->get('arrival_code')) ? $request->get('arrival_code') : $this->getArrivalCodes();
        
        // 获取符合查询条件的班级数据
        $data = $this->getDormsCollectList($currentPage, $rows, $keywords, $enrollment_directory, $arrival_code);
        
        if (!$data->isEmpty()) {
            $formatList = array();
            $count = $data->total() > 0 ? $data->total() : 0;
            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $exam_code = $item['exam_code'];
                    $formatItem['exam_code'] = $exam_code;
                    $student = $this->getNewStudentByCode($exam_code);
                    $formatItem['student_name'] = $student['name'];
                    $formatItem['sex'] = $this->formatStudentSex($student['sex']);
                    $formatItem['card_number'] = $student['card_number'];
                    $formatItem['enrollment_directory'] = $student['enrollment_directory'];
                    $formatItem['address'] = $item['detail_address'];
                    $formatItem['apply_reason'] = $item['apply_reason'].$item['other_reason'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }
                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }
        return $response;
    }


    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的迎新列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getDormsCollectList($page = 1, $rows, $keywords, $enrollment_directory, $arrival_code)
    {
        if($enrollment_directory == '' || empty($enrollment_directory)){
            //不存在根据指定字段排序
            if (!isset($keywords) || empty($keywords)) {
                $data = ApplyDorms::orderBy('created_at', 'desc')
                        ->where('arrival_code', 'like', '%' . $arrival_code . '%')
                        ->paginate($rows, ['*'], 'page', $page);
            } else {
                $Info = NewStudent::where('name','like','%' . $keywords . '%')
                        ->get();
                $StudentCodeArray = array();
                for($i=0;$i<count($Info);$i++){
                    if(!in_array($Info[$i]->exam_code, $StudentCodeArray)){
                        $StudentCodeArray[] = $Info[$i]->exam_code;
                    }
                }
                $data = ApplyDorms::whereIn('exam_code', $StudentCodeArray)
                    ->where('arrival_code', 'like', '%' . $arrival_code . '%')
                    ->orWhere('exam_code', 'like', '%' . $keywords . '%')
                    ->orderBy('created_at', 'desc')
                    ->paginate($rows, ['*'], 'page', $page);
            }
        }else{
            //获取接收参数"招生目录"下的学生code集合
            $StudentInfo = NewStudent::where('enrollment_directory', $enrollment_directory)->get();
            $StudentCodeArray = array();
            for($i=0;$i<count($StudentInfo);$i++){
                if(!in_array($StudentInfo[$i]->exam_code, $StudentCodeArray)){
                    $StudentCodeArray[] = $StudentInfo[$i]->exam_code;
                }
            }
            
            //不存在根据指定字段排序
            if (!isset($keywords) || empty($keywords)) {
                $data = ApplyDorms::whereIn('exam_code', $StudentCodeArray)
                        ->where('arrival_code', 'like', '%' . $arrival_code . '%')
                        ->orderBy('created_at', 'desc')->paginate($rows, ['*'], 'page', $page);
            } else {
                $StudentCodeArray2 = array();
                //筛选名字关键字所有exam_code集合
                $Info1 = NewStudent::where('name','like','%' . $keywords . '%')->get();
                for($i=0;$i<count($Info1);$i++){
                    if(!in_array($Info1[$i]->exam_code, $StudentCodeArray2)){
                        $StudentCodeArray2[] = $Info1[$i]->exam_code;
                    }
                }
                //筛选考试号exam_code关键字所有exam_code集合
                $Info2 = NewStudent::where('exam_code','like','%' . $keywords . '%')->get();
                for($i=0;$i<count($Info2);$i++){
                    if(!in_array($Info2[$i]->exam_code, $StudentCodeArray2)){
                        $StudentCodeArray2[] = $Info2[$i]->exam_code;
                    }
                }
                //将共有的exam_code取出 -> 最终结果 $FinalData
                for($a=0;$a<count($StudentCodeArray);$a++){
                    for($b=0;$b<count($StudentCodeArray2);$b++){
                        if($StudentCodeArray[$a] == $StudentCodeArray2[$b]){
                            $FinalData[] = $StudentCodeArray[$a];
                        }
                    }
                }
                $data = ApplyDorms::whereIn('exam_code', $FinalData)
                    ->where('arrival_code', 'like', '%' . $arrival_code . '%')
                    ->orderBy('created_at', 'desc')
                    ->paginate($rows, ['*'], 'page', $page);
            }
        }
        
        Log::info('da',['da'=>$data]);
        return $data;
    }

    /***
     * 根据学生考试号获取学生详细信息
     * @param $code
     * @return mixed
     */
    private function getNewStudentByCode($code)
    {
        $student = NewStudent::where('exam_code', $code)->first();
        return $student;
    }

    /***
     * 检测是否缴费
     * @param $code
     * @return mixed
     */
    private function formatStudentSex($val)
    {
        if ($val == 1) {
            return '男';
        } elseif ($val == 2) {
            return '女';
        } else {
            return '';
        }
    }
    /**
     * 获取所有招生年份
     *
     * @param $code
     * @return mixed|string
     */
    private function getEnrollmentCodes()
    {
        $codes = NewArrival::all()->pluck('code')->toArray();
        return $codes;
    }
    
    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCodes()
    {
        $code = '';
        $years = NewArrival::where('isOn',true)->first();
        if (!empty($years) || isset($years)) {
            $code = $years->code;
        }
        return $code;
    }

}
